#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
监控模块 - 用于收集和报告性能统计信息
"""

import time
import threading
from typing import Dict, Any, List
from config import load_config
from logger import setup_logger

logger = setup_logger("monitoring")

class PerformanceMonitor:
    """性能监控类，用于收集和报告统计信息"""
    
    def __init__(self):
        """初始化性能监控器"""
        self.stats = {
            "tcp": {
                "total_connections": 0,
                "active_connections": 0,
                "bytes_sent": 0,
                "bytes_received": 0,
                "connection_errors": 0
            },
            "udp": {
                "total_clients": 0,
                "active_clients": 0,
                "bytes_sent": 0,
                "bytes_received": 0,
                "client_errors": 0
            },
            "start_time": time.time(),
            "uptime": 0
        }
        self.lock = threading.RLock()
        self.config = load_config()
        self.monitoring_enabled = self.config.get("monitoring", {}).get("enabled", True)
        self.stats_interval = self.config.get("monitoring", {}).get("stats_interval", 60)
        
        # 启动统计报告线程
        if self.monitoring_enabled:
            self.stop_event = threading.Event()
            self.stats_thread = threading.Thread(target=self._report_stats_periodically, daemon=True)
            self.stats_thread.start()
    
    def update_tcp_stats(self, field: str, value: int = 1) -> None:
        """
        更新TCP统计信息
        
        Args:
            field: 要更新的字段
            value: 更新的值
        """
        if not self.monitoring_enabled:
            return
            
        with self.lock:
            if field in self.stats["tcp"]:
                self.stats["tcp"][field] += value
    
    def update_udp_stats(self, field: str, value: int = 1) -> None:
        """
        更新UDP统计信息
        
        Args:
            field: 要更新的字段
            value: 更新的值
        """
        if not self.monitoring_enabled:
            return
            
        with self.lock:
            if field in self.stats["udp"]:
                self.stats["udp"][field] += value
    
    def get_stats(self) -> Dict[str, Any]:
        """
        获取当前统计信息
        
        Returns:
            Dict[str, Any]: 统计信息字典
        """
        with self.lock:
            # 更新运行时间
            self.stats["uptime"] = time.time() - self.stats["start_time"]
            return self.stats.copy()
    
    def _report_stats_periodically(self) -> None:
        """定期报告统计信息"""
        while not self.stop_event.is_set():
            time.sleep(self.stats_interval)
            stats = self.get_stats()
            
            logger.info("性能统计信息:")
            logger.info(f"运行时间: {stats['uptime']:.2f} 秒")
            
            tcp_stats = stats["tcp"]
            logger.info("TCP 统计:")
            logger.info(f"  总连接数: {tcp_stats['total_connections']}")
            logger.info(f"  活动连接: {tcp_stats['active_connections']}")
            logger.info(f"  发送字节: {tcp_stats['bytes_sent']}")
            logger.info(f"  接收字节: {tcp_stats['bytes_received']}")
            logger.info(f"  连接错误: {tcp_stats['connection_errors']}")
            
            udp_stats = stats["udp"]
            logger.info("UDP 统计:")
            logger.info(f"  总客户端: {udp_stats['total_clients']}")
            logger.info(f"  活动客户端: {udp_stats['active_clients']}")
            logger.info(f"  发送字节: {udp_stats['bytes_sent']}")
            logger.info(f"  接收字节: {udp_stats['bytes_received']}")
            logger.info(f"  客户端错误: {udp_stats['client_errors']}")
    
    def stop(self) -> None:
        """停止监控"""
        if self.monitoring_enabled:
            self.stop_event.set()
            if hasattr(self, 'stats_thread') and self.stats_thread.is_alive():
                self.stats_thread.join(timeout=1)

# 创建全局监控实例
monitor = PerformanceMonitor()